package com.ssb.controller;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.client.LogClient;
import com.apache.excp.core.model.ExportVo;
import com.apache.ius.common.CommonUtils;
import com.apache.ius.controller.BaseAction;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.passport.common.DesUtils;
import com.apache.passport.entity.Token;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.portal.task.ScheduledExecutor;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.DataMap;
import com.apache.tools.RequestTools;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;
import com.apache.uct.common.entity.User;
import com.ssb.task.CashOutExcelImpTask;
import com.ssb.task.StatisticsChannelExcelImpTask;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

@Controller
@RequestMapping({"/"})
public class IndexAction extends BaseAction {
    /**
    * 欢迎首页
    */
    @RequestMapping(value = "/", method = RequestMethod.GET)
        public String index(HttpServletRequest request) throws ServletException, IOException {
        return "/WEB-INF/pages/ssb/admin/index";
    }

    /**
     * 管理端登录（/res/*配置在白名单内）
     */
    @RequestMapping(value = "/res/login", method = RequestMethod.POST)
    @ResponseBody
    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("request url -->" + request.getRequestURI());
        ResultMsg msg = new ResultMsg("F", "登录失败");
        Map<String, String> params = this.getParameterMap(request);
        Map<String, Object> maps = new HashMap<String, Object>();
        String username = params.get("username");
        String password = params.get("password");

        //验证码判断
        msg = checkRandCode(request, params);
        if (null != msg) {
            gotoErrorPage(request, response, msg.getMsg());
            return;
        }

        //登录账号判断
        if (StrUtil.isNull(username) || StrUtil.isNull(password)) {
            msg = new ResultMsg("F", "用户名或密码不能为空");
            gotoErrorPage(request, response, msg.getMsg());
            return;
        }
        maps.put("userEname", username);
        maps.put("Client-IP", StrUtil.doNull(params.get("Client-IP"), RequestTools.getIp(request)));
        maps.put("userPass", password);
        maps.put("sysEname", ToolsUtil.getInstance().getValueByKey("sysEname"));
        maps.put("addressIP", maps.get("Client-IP"));
        ResultEntity entity = LoadRpcService.service()
                .doServiceClient("ssoService", "outSideSocketLoginService", maps,
                        PortalPubFactory.getInstance().getRpcInfo("sso"));
        //解析sso返回登录结果
        JSONObject resObj = new JSONObject();
        if (entity != null && ("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
            if (entity.getEntity() instanceof String) {
                String userMsg = String.valueOf(entity.getMessage());
                log.error("登录提示：" + userMsg);

                if (userMsg.indexOf("用户已停用") > -1) {
                    msg = new ResultMsg("F", "您的账户未启用！");
                } else if (userMsg.indexOf("删除") > -1) {
                    msg = new ResultMsg("F", "您的账户已关闭登录操作，请联系管理人员！");
                } else {
                    if ("密码错误".equals(userMsg) || "用户不存在".equals(userMsg)) {
                        msg = new ResultMsg("F", "用户登录信息有误");
                    } else {
                        msg = new ResultMsg("F", userMsg);
                    }
                }
                resObj = JSONObject.fromObject(msg);
            } else {
                //仓储cookie
                Token token = (Token) entity.getEntity();
                Cookie cookie = new Cookie(ToolsUtil.getInstance().getValueByKey("cookieName"),
                        token.getTokenId());
                cookie.setPath("/");
                cookie.setMaxAge(-1);
                Cookie ucsso = new Cookie("_uc.sso",
                        DesUtils.getInstance().decrypt(token.getUserEname()));
                ucsso.setPath("/");
                ucsso.setMaxAge(-1);
                request.getSession().removeAttribute("loginUser");
                request.getSession().removeAttribute("tokenId");

                msg = new ResultMsg("T", "登录成功");

                //剔除loginInfo，解密email，userEname，mobile传明文
                JsonConfig jc = new JsonConfig();
                String config[] = {"loginInfo"};
                jc.setExcludes(config);
                String token_email = token.getEmail();
                String token_mobile = token.getMobile();
                String token_userEname = token.getUserEname();
                token.setEmail(DesUtils.getInstance().decrypt(token_email));
                token.setMobile(DesUtils.getInstance().decrypt(token_mobile));
                token.setUserEname(DesUtils.getInstance().decrypt(token_userEname));
//                msg = new ResultMsg("T", JSONObject.fromObject(token, jc).toString());
                resObj = JSONObject.fromObject(msg, jc);
                //存储session
                if ("T".equals(msg.getFlag())) {
                    JSONObject jb = JSONObject.fromObject(token);
                    Map<String, Object> map = (Map) jb;
                    LoginUser loginUser = PBOSSOTools.getLoginUserFromUserCenter(String.valueOf(map.get("userEname")),
                            String.valueOf(map.get("tokenId")));
                    if (loginUser != null) {
                        jb.put("sysFlag", loginUser.getSysFlag());
                        User user = loginUser.getUser();
                        if (user != null) {
                            Integer userSore = user.getUserScore();
                            if ((!"manager".equals(token.getUserType()) && !"broker".equals(token.getUserType()))) {
                                msg = new ResultMsg("F", "此账号暂无权限登录");
                                gotoErrorPage(request, response, msg.getMsg());
                                return;
                            }
                            jb.put("auditStatus", StrUtil.doNull(user.getAuditStatus(), ""));
                            jb.put("appId", StrUtil.doNull(user.getAppUid(), ""));
                            jb.put("userScore", userSore);
                        }
                    }
                    resObj.put("loginUser", jb);

                    response.addCookie(cookie);
                    response.addCookie(ucsso);
                    request.getSession().setAttribute("tokenId", token.getTokenId());
                    request.getSession().setAttribute("loginUser", loginUser);
                }
                log.info("[" + username + "]登录成功！");

                //记录日志
                Map<String, Object> logMap = new HashMap<String, Object>();
                logMap.put("logOperationType", "login");
                logMap.put("logClassName", User.class.getName());
                logMap.put("logIp", maps.get("Client-IP"));
                logMap.put("log_userEname", token.getUserEname());
                log.info("登录成功日志：" + logMap);
                LogClient.getInstance().execute(logMap);//添加日志

            }
        }
        log.info("[" + username + "]登录结果：" + msg.toString());
        this.outputJson(resObj.toString(), response, "");
    }

    /**
     * description:  验证验证码
     */
    private ResultMsg checkRandCode(HttpServletRequest request, Map<String, String> params) {
        String if_randCode = StrUtil.doNull(CommonUtils.getConfigVal("if_randCode"), "T");
        if ("F".equals(if_randCode)) {
            return null;
        }
        ResultMsg msg = null;
        String session_randCode = String.valueOf(request.getSession().getAttribute("randCode"));
        if (ToolsUtil.isNull(session_randCode))
            return null;
        if ((StrUtil.isNull(params.get("rand")))) {
            msg = new ResultMsg("F", "验证码不能为空");
            return msg;
        }
        if (!params.get("rand").equals(session_randCode)) {
            msg = new ResultMsg("F", "验证码错误");
            return msg;
        }
        return msg;
    }
    /**
     * description: 导出excel
     * templateName 模板名称（必要）
     * pageName
     * formName
     *
     */
    @RequestMapping(value = "/outexcel", method = RequestMethod.POST)
    @ResponseBody
    protected ResultMsg outexcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultMsg msg = new ResultMsg("F", "操作失败");
        Map<String, String> parameterMap = this.getParameterMap(request);
        Map<String,Object> reqMap = new HashMap<>();
        for (String key :parameterMap.keySet()){
            reqMap.put(key,parameterMap.get(key));
        }
        reqMap.put("page","0");
        reqMap.put("rows","0");
        ExportVo vo = new ExportVo();
        String filePath = ToolsUtil.getClassLoaderPath()                        //本地路径好的
                .replace("/WEB-INF/classes/", "/loadFile-out/")+"static/outexcel/";
        vo.setFilePath(filePath);
        String fileName = new Date().getTime()+".xls";
        vo.setNewFileName(fileName);
        vo.setTemplateName(reqMap.get("templateName").toString());
        Map<String,Object> whereMap = new HashMap<>();
        whereMap.put("result_column","ssInsurCpy.insurCode,ssInsurCpy.insurFullName");
        ResultEntity resultEntity = IusPluginUtil.getInstance().select("ssb","list", "s_ssInsurCpy", whereMap);
        Map<String,String> dictMap = new HashMap<>();
        if(!Validator.isEmpty(resultEntity.getEntity())){
            List<DataMap> list = (List<DataMap>)resultEntity.getEntity();
            if(list.size()>0){
                for (DataMap data:list) {
                    dictMap.put(String.valueOf(data.get("insurCode")),String.valueOf(data.get("insurFullName")));
                }
            }
        }


        StatisticsChannelExcelImpTask task1 = new StatisticsChannelExcelImpTask(reqMap.get("objName").toString(),dictMap, reqMap, vo);
        Future<Integer> future1 = ScheduledExecutor.newInstance().getService().submit(task1);
        try {
            if (future1.get() > 0) {
                String path_ = request.getContextPath();
                String basePath_ =
                        request.getScheme() + "://" + request.getServerName() + ":" + request
                                .getServerPort() + path_ + "/outexcel/" + fileName;
                msg = new ResultMsg("T", basePath_);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return new ResultMsg("F", "导出出错");
        }
        return msg;
    }
    /**
     * description: 提现审核
     * templateName 模板名称（必要）
     * pageName
     * formName
     *
     */
    @RequestMapping(value = "/outCashExcel", method = RequestMethod.POST)
    @ResponseBody
    protected ResultMsg outCashExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultMsg msg = new ResultMsg("F", "操作失败");
        Map<String, String> parameterMap = this.getParameterMap(request);
        Map<String,Object> reqMap = new HashMap<>();
        for (String key :parameterMap.keySet()){
            reqMap.put(key,parameterMap.get(key));
        }
//        reqMap.put("page","0");
//        reqMap.put("rows","0");
        ExportVo vo = new ExportVo();
        String filePath = ToolsUtil.getClassLoaderPath()                        //本地路径好的
                .replace("/WEB-INF/classes/", "/loadFile-out/")+"static/outexcel/";
        vo.setFilePath(filePath);
        String fileName = new Date().getTime()+".xls";
        vo.setNewFileName(fileName);
        vo.setTemplateName(reqMap.get("templateName").toString());
        Map<String,String> dictMap = readDictionary("auditstatus");

        CashOutExcelImpTask task1 = new CashOutExcelImpTask(reqMap.get("objName").toString(),dictMap, reqMap, vo);
        Future<Integer> future1 = ScheduledExecutor.newInstance().getService().submit(task1);
        try {
            if (future1.get() > 0) {
                String path_ = request.getContextPath();
                String basePath_ =
                        request.getScheme() + "://" + request.getServerName() + ":" + request
                                .getServerPort() + path_ + "/outexcel/" + fileName;
                msg = new ResultMsg("T", basePath_);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return new ResultMsg("F", "导出出错");
        }
        return msg;
    }
    public Map<String,String> readDictionary(String fileName) throws IOException {
        Map<String,String> map= new HashMap<>();
        JSONArray json = null;
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader bufferedReader = null;
        File filePath = new File(ToolsUtil.getClassLoaderPath()+"/static/js/dictData/dict-data-"+fileName+".js");
        try {
            fis = new FileInputStream(filePath);
            isr = new InputStreamReader(fis, "UTF-8");
            bufferedReader = new BufferedReader(isr);
            String str = bufferedReader.readLine();
            if (str != null) {
                json = JSONArray.fromObject(str);
                for (int i = 1; i < json.size(); i++) {
                    JSONObject obj = json.getJSONObject(i);
                    map.put(String.valueOf(obj.get("id")),String.valueOf(obj.get("text")));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
        return map;
    }
}


